package home.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import home.dao.HomeDAO;
import home.dao.impl.HomeDAOJdbcImpl;
import home.domain.Home;

public class HomeServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    
    private HomeDAO homeDAO=new HomeDAOJdbcImpl();

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	String uri = request.getRequestURI();
        String path = uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        /**根据用户提交的请求与对应的业务逻辑进行匹配判断*/
        if(path.equals("/add")){
            add(request,response);
        }else if(path.equals("/delete")){
        	delete(request,response);
        }else if(path.equals("/query")){
        	query(request,response);
        }
  }

	private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        		
		try{
        	homeDAO.delete();
        }catch(Exception e){}
		request.getRequestDispatcher("Home.jsp").forward(request, response);
    }

    private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
       List<Home> homes=homeDAO.getAll();
       
       request.setAttribute("homes", homes);
       
       request.getRequestDispatcher("Query.jsp").forward(request, response);
    }

    private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setCharacterEncoding("UTF-8");
    	
    	String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String sex = request.getParameter("sex");
        String address = request.getParameter("address");
        
        Home home = new Home(name,phone,sex,address);
        homeDAO.save(home);
        
    	System.out.println(request.getParameter("name"));
    	request.getRequestDispatcher("add.jsp").forward(request, response);
    }
}